﻿ 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
using GCELibrary.Current;
using System.Web.UI;
 
using Newtonsoft.Json;
using System.Web;
using ZF.BLL;
using ZF.DAL;
using ZF.Model;
namespace ZF.BLL.Gate
{

 
    public abstract class GateBase
    {
 
        #region 常量&变量
        protected const string LoginErrCountMsg = "您密码错误次数过多，一段时间内将不能登录，请联系系统管理员！";
        protected const string AccountOrPwdErrMsg = "帐号或密码错误";
        protected const string AccountOverdueMsg = "该用户已经过期，如需要继续使用，请联系管理员！";
        protected ZFDataContext dataContext = null;
        protected SiteInfo SiteInfo = SiteInfo.Instance;

        public abstract string DefaultPage { get; set; }
        public abstract string LoginPage { get;}

        #endregion

        #region 构造&析构
        public GateBase()
        {
            dataContext = BLL.SiteInfo.CreateDBDataContext();
        }
        ~GateBase()
        {
            dataContext.Connection.Close();
            dataContext.Connection.Dispose();
            dataContext.Dispose();
        }
        #endregion

        #region 登入登出
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public virtual bool Login(string account, string password, out string msg)
        {

            var dc = dataContext;
            var member = dc.US_Member.FirstOrDefault(u => u.Account == account);
            if (!(member != null && member.Pwd == SiteInfo.EncryptBase64( password)))//验证帐号密码
            {
                msg = AccountOrPwdErrMsg; return false;
            }

            if (!CheckValidity(member, out msg))//验证用户合法性
                return false;
            var memberModel = this.LoadUserInfo(member);
            RegisterUser(memberModel);//注册登录
            
            msg = "";
            return true;

        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="account"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public virtual bool Login(string account, string password,int days)
        {
            string msg = "";
            bool result = Login(account, password, out msg);

            if (result)
            {
                //写入cookies
                WriteCookie(account, password, days);
                GoDefaultPage();
            }
            else
                AlertMsg(msg);
            return result;
        }
        /// <summary>
        ///  用户注销
        /// </summary>
        /// <param name="user"></param>
        public virtual bool Logout(IMember member)
        {
            if (member != null)
            {
                RemoveCookie();
                //WriteOffOnLine(member);// 注销在线
                WriteOffUserInfo(member);//清除用户信息
            }
            GoLoginPage();//转到登录页面
            return false;
        }

        #endregion

        #region 验证
        /// <summary>
        /// 验证登录类型
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        protected abstract bool CheckLoginUserType(US_Member member);
        //{
        //    return true;
        //    var siteType = SiteInfo.GetCurrentSiteType();
        //    UserGroupType userType = key.Convert<UserGroupType>();
        //    if (siteType == SiteType.ManageSite)
        //        return (userType & UserGroupType.System) == UserGroupType.System;
        //    else if (siteType == SiteType.MonitorSite)
        //    {
        //        return (userType & UserGroupType.Company) == UserGroupType.Company
        //            || (userType & UserGroupType.Personal) == UserGroupType.Personal;
        //    }
        //    throw new Exception("protected virtual bool CheckLoginUserType(string key)");
        //}
        /// <summary>
        /// 验证用户有效性
        /// </summary>
        /// <param name="user"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        protected bool CheckValidity(US_Member member, out string msg)
        {
            var result = CheckLoginUserType(member);
            if (!result)
            {
                msg = "非法帐号";
                return false;
            }
            else
            {
                if (member.Status == 1)
                {
                    msg = "登录成功";
                    return true;
                }
                else
                {
                    msg = "用户不可用";
                    return false;
                }
            }
        }
        #endregion

        #region 其它

        /// <summary>
        /// 创建用户模型，这里根据登录用户类型进行抽像。
        /// </summary>
        /// <returns></returns>
        protected abstract MemberBase CreateUserInfoModel();
        //{
        //    return new GeneralMember()
        //    {
                 
        //    };


        //    //var siteType = SiteInfo.GetCurrentSiteType();
        //    //if (siteType == SiteType.ManageSite)
        //    //{
        //    //    return new SysUser();
        //    //}
        //    //else if (siteType == SiteType.MonitorSite)
        //    //{
        //    //    return new MonitorUser();
        //    //}
        //    //throw new Exception("protected virtual UserBase CreateUserInfoModel()");
        //}

        /// <summary>
        /// 显示提示信息
        /// </summary>
        /// <param name="msg"></param>
        protected virtual void AlertMsg(string msg)
        {

            HttpContext.Current.Response.Write(string.Format("<script>alert('{0}');history.go(-1)</script>", msg));
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 写登入日志
        /// </summary>
        /// <param name="user"></param>
        protected void WriteLoginLog(IMember user)
        {
            SiteInfo.InsertLog("用户登录:" + user.Account, string.Format("用户:{0},在{1}登录{2}站点,登录ip为:{3}",
                user.Account, DateTime.Now, "-", user.LoginIp));
        }
        /// <summary>
        /// 写登出日志
        /// </summary>
        /// <param name="user"></param>
        protected void WriteLogoutLog(IMember user)
        {
            SiteInfo.InsertLog("用户登出:" + user.Account, string.Format("用户:{0},在{1}登出{2}站点,登出ip为:{3}",
                user.Account, DateTime.Now, "-", user.LoginIp));
        }
        /// <summary>
        /// 写入cookies信息
        /// </summary>
        /// <param name="account"></param>
        /// <param name="pwd"></param>
        /// <param name="days"></param>
        protected void WriteCookie(string account,string pwd, int days)
        {
            if (days > 0)
            { 
                var ck=AppKey.CookieKey;
                var token = new HttpCookie(ck.Token);
                token.Domain = HttpContext.Current.Request.Url.Host;
                token.Values.Add(ck.Account, account);
                token.Values.Add(ck.Passowrd, SiteInfo.EncryptBase64(pwd));
                token.Expires = DateTime.Now.AddDays(days);
                HttpContext.Current.Response.Cookies.Add(token);
          
            }
        }
        public void RemoveCookie()
        {
            HttpContext.Current.Response.Cookies[AppKey.CookieKey.Token].Value = null;
        }
        #endregion

        #region 页面跳转
        /// <summary>
        /// 转到默认页
        /// </summary>
        public virtual void GoDefaultPage()
        {
            HttpContext.Current.Response.Redirect(DefaultPage);
            //throw new Exception();
            //var siteType = SiteInfo.GetCurrentSiteType();
            //if (siteType == SiteType.ManageSite)
            //{
            //    HttpContext.Current.Response.Redirect(SiteInfo.SystemConfig.SystemFramePage);
            //}
            //else if (siteType == SiteType.MonitorSite)
            //{

            //    var rPath = "";

            //    if (SiteInfo.GetCurrentClientInfo().IsMobile)
            //    {
            //        rPath = SiteInfo.SystemConfig.MobileMonitorDefaultPage;
            //    }
            //    else
            //    {
            //        var cu = SiteInfo.GetCurrentUser();
            //        //这里根据当前登录用户的权限来判断转到哪个页面，如果监控权限则转到默认页
            //        if (SiteInfo.CheckModuleRight(cu, BLL.ModuleType.RealMonitor))
            //            rPath = SiteInfo.SystemConfig.NetMonitorDefaultPage;
            //        else if (SiteInfo.CheckModuleRight(cu, BLL.ModuleType.CustomerService))
            //            rPath = SiteInfo.SystemConfig.CustomerServiceDefaultPage;
            //        else if (SiteInfo.CheckModuleRight(cu, BLL.ModuleType.CompanyShow))
            //            rPath = SiteInfo.SystemConfig.CompanyShowDefaultPage;
            //        else
            //            rPath = SiteInfo.SystemConfig.MonitorSiteDefaultPage;

            //    }

            //    //var url = SiteInfo.GetCurrentClientInfo().IsMobile ? SiteInfo.SystemConfig.MobileMonitorDefaultPage :
            //    //    SiteInfo.SystemConfig.NetMonitorDefaultPage;
            //    HttpContext.Current.Response.Redirect(rPath);
            //}
        }
        /// <summary>
        /// 转到登录页面
        /// </summary>
        public virtual void GoLoginPage()
        {

            var js = @"
<script>
    window.location = '{0}';
    window.parent.location = '{0}';
</script>";
            HttpContext.Current.Response.Write(string.Format(js, LoginPage));
            HttpContext.Current.Response.End();
            //HttpContext.Current.Response.Redirect(DefaultPage);
            //throw new Exception();
            //var siteType = SiteInfo.GetCurrentSiteType();
            //if (siteType == SiteType.ManageSite)
            //{
            //    HttpContext.Current.Response.Write(
            //    string.Format("<script>window.parent.location='{0}';</script>", SiteInfo.Instance.SystemConfig.SystemLoginPage));
            //    HttpContext.Current.Response.End();
            //}
            //else if (siteType == SiteType.MonitorSite)
            //{

            //    //判断是否手机，如果手机客户端则使用手机登录页面
            //    var url = SiteInfo.GetCurrentClientInfo().IsMobile ? SiteInfo.Instance.SystemConfig.MobileMonitorLoginPage :
            //    SiteInfo.SystemConfig.NetMonitorLoginPage;
            //    HttpContext.Current.Response.Redirect(url);

            //}

        }
        #endregion 

        #region 用户信息
        /// <summary>
        /// 加载用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        protected virtual MemberBase LoadUserInfo(Model.US_Member user)
        {
            var mm = CreateUserInfoModel();
            
            mm.Account = user.Account;
            mm.Password = user.Pwd;
            mm.FullName = user.Contact;
            mm.MemberId = user.MemberId;
            mm.Phone = user.Phone;
            mm.QQ = user.QQ;
            mm.EMail = user.Email;
            mm.Tel = user.Tel;
            mm.Zipcode = user.Zipcode;
            mm.Address = user.Address;
            mm.Integral = user.Integral;
            mm.IsExpert = user.IsExpert;
            mm.IsMedium = user.IsMedium;
            
            return mm;

    
             
        }
        /// <summary>
        /// 注册登录用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        protected virtual void RegisterUser(IMember user)
        {
            RegisterUserInfo(user);//注册用户信息写入session
            //RegisterOnLine(user);//注册在线
            WriteLoginLog(user);//写登录日志
        }
        /// <summary>
        /// 注册在线
        /// </summary>
        protected void RegisterOnLine(IMember user)
        {
            throw new Exception();
            // 注册在线
            //SiteInfo.OnlineUserManage.CreateOnlineUser((UserBase)user);
        }
        /// <summary>
        /// 注册用户信息，这里写入session
        /// </summary>
        /// <param name="user"></param>
        protected void RegisterUserInfo(IMember user)
        {
            // 写入session
            GCELibrary.Current.HttpSession.SetSession(AppKey.SessionKey.CurrentUser, user);
        }
        /// <summary>
        /// 清除用户在线
        /// </summary>
        /// <param name="user"></param>
        protected void WriteOffUserInfo(IMember user)
        {
            HttpSession.SetSession(AppKey.SessionKey.CurrentUser, null);
            WriteLogoutLog(user);//写登录日志
        }

        /// <summary>
        /// 注销在线
        /// </summary>
        protected void WriteOffOnLine(IMember user)
        {
            throw new Exception();
            // 注销在线
            //SiteInfo.OnlineUserManage.RemoveOnlineUser(System.Web.HttpContext.Current.Session.SessionID);
        }
        #endregion
    }
    public class ManageGate : GateBase
    {
        public override string LoginPage
        {
            get { return string.Format("/{0}/Login.aspx", AppKey.SiteKey.ManageDirectory); }
        }
        private string _Url = string.Format("{0}/frame.aspx", AppKey.SiteKey.ManageDirectory);
        public override string DefaultPage
        {
            get
            {
                return _Url;
            }
            set
            {
                _Url = value;
            }
        }

        protected override MemberBase CreateUserInfoModel()
        {
            return new ManageMember();
        }

        protected override MemberBase LoadUserInfo(US_Member user)
        {
            var result = base.LoadUserInfo(user); ;
            var mm = (ManageMember)result;
            mm.RightModules = user.Right.EmptyString("").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
            return result;
        }

        protected override bool CheckLoginUserType(Model.US_Member member)
        {
           
            return member.Type == 100;
        }
    }
    public class GeneralGate : GateBase
    {
        public override string LoginPage
        {
            get { return "/Login.aspx"; }
        }
        private string _Url = "/Person/frame.aspx";
        public override string DefaultPage
        {
            get
            {
                return _Url;
            }
            set
            {
                _Url = value;
            }
        }
        protected override MemberBase CreateUserInfoModel()
        {
            return new GeneralMember();
        }
        protected override bool CheckLoginUserType(Model.US_Member member)
        {

            return true;
        }
 
    }


}
